package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.Student;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.utils.RoleEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminService {
@Resource
    private AdminMapper adminMapper;
    /**登录
     *
     */
    @Transactional
    public Account login(Account account){
        Account dbAdmin =adminMapper.selectByUsername(account.getUsername());
        if(dbAdmin == null ){
            //没有用户
            throw new CustomException("账号或密码错误");
        }
        //比较密码
        if(!account.getPassword().equals(dbAdmin.getPassword())){
            throw new CustomException("账号或密码错误");
        }
        //登录成功
        return dbAdmin;

    }

    // 添加学生信息
    public void add(Admin admin) {
        Admin dbStudent = adminMapper.selectByUsername(admin.getUsername());
        if (dbStudent != null) {
            // 已有账号，不允许注册
            throw new CustomException("账号已存在");
        }
        if (ObjectUtil.isEmpty(admin.getName())) {
            admin.setName(admin.getUsername());
        }
        admin.setRole(RoleEnum.TEACHER.name());
        adminMapper.insert(admin);
    }

    // 根据ID更新学生信息
    public void updateById(Admin admin) {
        adminMapper.updateById(admin);
    }

    // 根据ID删除学生信息
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    // 分页查询学生信息列表
    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
        PageHelper.startPage(pageNum, pageSize); // 设置分页信息
        List<Admin> studentList = adminMapper.selectAll(admin); // 查询学生信息列表
        return PageInfo.of(studentList); // 返回分页信息
    }

}
